package cn.iocoder.yudao.module.business.client;


import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.date.DateUtils;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.module.business.controller.admin.trainUnit.vo.TrainUnitPageReqVO;
import cn.iocoder.yudao.module.business.dal.dataobject.trainUnit.TrainUnitDO;
import cn.iocoder.yudao.module.business.enums.AppConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * OAuth 2.0 客户端
 * <p>
 * JszxClient
 */
@Component
@Slf4j
public class ZljcClient {

    private static final String BASE_URL = "http://192.168.1.138:8003/zljc";
    private static final String LOGIN_URL = "/admin-api/system/oauth2/token";
    private static final String TRAIN_UNIT = "/admin-api/open/project/trainUnitPage";

    /**
     * 租户编号
     * <p>
     * 默认使用 1；如果使用别的租户，可以调整
     */
    public static final String TENANT_ID = "1";

    private static final String CLIENT_ID = "zljc-sso";
    private static final String CLIENT_SECRET = "xztr6t8qbpcmnfujdfe8xc8schcbyjf6";
    private static final String GRANT_TYPE = "password";
    private static final String USERNAME = "openuser";
    private static final String PASSWORD = "Zljc@open2024";

    private static final long INVOKE_TIMEOUT_MILLIS = 120 * DateUtils.SECOND_MILLIS;



    /**
     * 请求质量监测的培训单位
     * @param index 页码
     * @param totalPage 页数
     * @param pageReqVO 请求参数
     * @return 培训单位列表
     */
    public static List<TrainUnitDO> getTrainUnit(int index, AtomicInteger totalPage, TrainUnitPageReqVO pageReqVO) {
        String params = "?syncType="+ pageReqVO.getSyncType() +  "&pageNo=" + index + "&pageSize=" + pageReqVO.getPageSize();

        CommonResult<?> commonResult = executeGetInvoke( TRAIN_UNIT + params,true);
        if (  AppConstants.SUCCESS == commonResult.getCode()){
            //获得结果
            String body = JsonUtils.toJsonString(commonResult.getData());
            JSONObject jsonObject = JSONUtil.parseObj(body);
            //设置总页码
            int total = jsonObject.getInt("total");
            if ( total == 0){
                totalPage.set(total);
            }else{
                int page = ( total / pageReqVO.getPageSize() ) + 1;
                totalPage.set(page);
            }
            //输出数据
            Object data = jsonObject.get("list");
            return JSONUtil.toList(JSONUtil.toJsonStr(data), TrainUnitDO.class);
        }else{
            return new ArrayList<>();
        }
    }



    /**
     * 执行单个任务的 HTTP POST请求调用
     *
     * @param requestParams body参数
     * @param url 请求地址
     * @param isAuth 是否需要token
     * @return HTTP 响应
     */
    public static CommonResult<?> executeSubmitInvoke(String requestParams, String url, Boolean isAuth) {

        // 发起请求
        try (HttpResponse response = HttpUtil.createPost(BASE_URL + url)
                .body(requestParams)
                .addHeaders(setHeaders(isAuth))
                .timeout((int)  INVOKE_TIMEOUT_MILLIS)
                .execute()) {
            // 解析结果
            return JsonUtils.parseObject(response.body(), CommonResult.class);
        }catch (Exception e){
            return CommonResult.error(AppConstants.ERROR,"请求异常");
        }
    }

    /**
     * 执行单个任务的 HTTP GET请求调用

     * @param url 请求地址
     * @param isAuth 是否需要token
     * @return HTTP 响应
     */
    public static CommonResult<?> executeGetInvoke(String url, Boolean isAuth) {

        // 发起请求
        try (HttpResponse response = HttpUtil.createGet(BASE_URL + url)
                .addHeaders(setHeaders(isAuth))
                .timeout((int)  INVOKE_TIMEOUT_MILLIS)
                .execute()) {
            // 解析结果
            return JsonUtils.parseObject(response.body(), CommonResult.class);
        }catch (Exception e){
            return CommonResult.error(AppConstants.ERROR,"请求异常");
        }
    }

    /**
     * 执行单个任务的 HTTP 登录请求调用
     * @return HTTP 响应
     */
    public static String executeLoginInvoke(){

        // 拼接 header 参数
        Map<String, String> headers = new HashMap<>();
        headers.put("tenant-id",TENANT_ID);

        //拼接参数
        String params = "?client_id="+CLIENT_ID+"&client_secret="+CLIENT_SECRET+"&grant_type=" + GRANT_TYPE + "&username=" + USERNAME + "&password=" + PASSWORD;

        // 发起请求
        try (HttpResponse response = HttpUtil.createPost(BASE_URL + LOGIN_URL + params)
                .addHeaders(headers)
                .timeout((int)  INVOKE_TIMEOUT_MILLIS)
                .execute()) {
            // 解析结果
            CommonResult<?> commonResult = JsonUtils.parseObject(response.body(), CommonResult.class);
            if (commonResult!=null  &&   AppConstants.SUCCESS == commonResult.getCode()){

                String body = JsonUtils.toJsonString(commonResult.getData());
                JSONObject jsonObject = JSONUtil.parseObj(body);

                return (String) jsonObject.get(AppConstants.CommonField.ACCESS_TOKEN);
            }else{
                return null;
            }
        }catch (Exception e){
            return null;
        }
    }

    /**
     * header参数设置
     * @param isAuth 是否需要登录
     */
    private static Map<String,String> setHeaders(boolean isAuth){
        Map<String, String> headers = new HashMap<>(16);
        headers.put("tenant-id",TENANT_ID);
        if (isAuth){
            headers.put("Authorization","Bearer " + executeLoginInvoke());
        }
        return headers;
    }

}
